package com.boomsecret.juc.executor;

import org.eclipse.jetty.util.BlockingArrayQueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/22.
 */
public class ExecutorCompletionServiceDemo {
    public static void main(String[] args) {
        int corePoolSize = 1;
        int maximumPoolSize = 1;
        long keepAliveTime = 0L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new BlockingArrayQueue<>(32);
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler);

        ExecutorCompletionService service = new ExecutorCompletionService(threadPoolExecutor);

        // 和Executor的submit没什么区别
        Future<String> future = service.submit(() -> {
            System.out.println("future start");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("future end");
            return "future response";
        });
        System.out.println("submit end");
        try {
            System.out.println(future.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("main end");
    }
}
